rm(list=ls())

# Normal Choroplath libs
library(tidyverse)
## -- Attaching packages --------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.2     v purrr   0.3.4
## v tibble  3.0.4     v dplyr   1.0.2
## v tidyr   1.1.2     v stringr 1.4.0
## v readr   1.4.0     v forcats 0.5.0
## -- Conflicts ------------------------------------------ tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(dplyr)
library(urbnmapr)
library(tmap)
library(sf)
## Warning: package 'sf' was built under R version 4.0.5
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(stringr)


# Leaflet Choroplath libs
library(leaflet)
library(tigris)
## Warning: package 'tigris' was built under R version 4.0.5
## To enable 
## caching of data, set `options(tigris_use_cache = TRUE)` in your R script or .Rprofile.
#webscrapping
library(rvest)
## 
## Attaching package: 'rvest'
## The following object is masked from 'package:readr':
## 
##     guess_encoding
data <- read.csv("state_2020.csv") 
data_1 <- data %>%
  select(State, Debt.Ratio..Total.Debts.Total.Assets) %>%
  rename("Debt_Level" = "Debt.Ratio..Total.Debts.Total.Assets")

#Debt was recorded as a character, converted to numeric
data_1$Debt_Level <- str_remove_all(string = data_1$Debt_Level, pattern = "%")
data_1$Debt_Level <- as.numeric(data_1$Debt_Level)



# removing DC as it is a district
states_sf <- get_urbn_map("states", sf = TRUE)
states_sf <- states_sf %>%
  filter(state_abbv != "DC")
# Debt levels by state
states_sf <- states_sf %>%
  rename(State = "state_name")

state_debt <- left_join(data_1, states_sf, by = "State")
head(state_debt)
##           State Debt_Level state_fips state_abbv                       geometry
## 1      Illinois      468.7         17         IL MULTIPOLYGON (((720075.7 -4...
## 2    New Jersey      441.7         34         NJ MULTIPOLYGON (((2057792 -28...
## 3   Connecticut      334.9         09         CT MULTIPOLYGON (((2156197 -83...
## 4 Massachusetts      305.5         25         MA MULTIPOLYGON (((2416684 359...
## 5      New York      273.8         36         NY MULTIPOLYGON (((2282929 -20...
## 6      Delaware      174.2         10         DE MULTIPOLYGON (((2056914 -28...
state_debt <- st_as_sf(state_debt)


position <- c("center", "top")
tm_shape(state_debt) + 
  tm_polygons(col = "Debt_Level", title = "Debt Level", palette = "Purples", breaks = c(0,25,50,75, 100, 150,200,300,400, 500)) +
  tm_text(text = "state_abbv", size = .75, remove.overlap = TRUE) +
  tm_legend(scale = .80) + 
  tm_layout(title = "State Debt Levels 2020 (%)", title.position = position) 

# webscraping credit ratings of each state from wikipedia

credit <- read_html("https://en.wikipedia.org/wiki/List_of_U.S._states_by_credit_rating")

credit_scores <- credit %>%
  html_nodes("table") %>%
  .[[3]] %>%
  html_table(fill = TRUE)

credit_scores <- credit_scores %>%
  select(State, '2020') %>%
  filter(State != "Source:[2]") %>%
  rename(Credit_Rating = "2020")

data_1 <- left_join(data_1, credit_scores, by = "State")
# Ask 
leaflet_map <- states(cb = TRUE)
## 
  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |====                                                                  |   5%
  |                                                                            
  |====                                                                  |   6%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=======                                                               |  10%
  |                                                                            
  |========                                                              |  11%
  |                                                                            
  |========                                                              |  12%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |=========                                                             |  13%
  |                                                                            
  |==========                                                            |  14%
  |                                                                            
  |===========                                                           |  15%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |============                                                          |  17%
  |                                                                            
  |============                                                          |  18%
  |                                                                            
  |=============                                                         |  18%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |==============                                                        |  19%
  |                                                                            
  |==============                                                        |  20%
  |                                                                            
  |===============                                                       |  21%
  |                                                                            
  |===============                                                       |  22%
  |                                                                            
  |================                                                      |  22%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |=================                                                     |  24%
  |                                                                            
  |=================                                                     |  25%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |===================                                                   |  27%
  |                                                                            
  |===================                                                   |  28%
  |                                                                            
  |====================                                                  |  28%
  |                                                                            
  |====================                                                  |  29%
  |                                                                            
  |=====================                                                 |  29%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |======================                                                |  31%
  |                                                                            
  |======================                                                |  32%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |========================                                              |  34%
  |                                                                            
  |========================                                              |  35%
  |                                                                            
  |=========================                                             |  36%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |==========================                                            |  38%
  |                                                                            
  |===========================                                           |  39%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |============================                                          |  41%
  |                                                                            
  |=============================                                         |  41%
  |                                                                            
  |=============================                                         |  42%
  |                                                                            
  |==============================                                        |  42%
  |                                                                            
  |==============================                                        |  43%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |===============================                                       |  45%
  |                                                                            
  |================================                                      |  45%
  |                                                                            
  |================================                                      |  46%
  |                                                                            
  |=================================                                     |  46%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |==================================                                    |  48%
  |                                                                            
  |==================================                                    |  49%
  |                                                                            
  |===================================                                   |  49%
  |                                                                            
  |===================================                                   |  50%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |====================================                                  |  51%
  |                                                                            
  |====================================                                  |  52%
  |                                                                            
  |=====================================                                 |  53%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |======================================                                |  55%
  |                                                                            
  |=======================================                               |  55%
  |                                                                            
  |=======================================                               |  56%
  |                                                                            
  |========================================                              |  57%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |=========================================                             |  58%
  |                                                                            
  |=========================================                             |  59%
  |                                                                            
  |==========================================                            |  59%
  |                                                                            
  |==========================================                            |  60%
  |                                                                            
  |==========================================                            |  61%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |===========================================                           |  62%
  |                                                                            
  |============================================                          |  62%
  |                                                                            
  |============================================                          |  63%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |=============================================                         |  65%
  |                                                                            
  |==============================================                        |  65%
  |                                                                            
  |==============================================                        |  66%
  |                                                                            
  |===============================================                       |  66%
  |                                                                            
  |===============================================                       |  67%
  |                                                                            
  |===============================================                       |  68%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |================================================                      |  69%
  |                                                                            
  |=================================================                     |  70%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |==================================================                    |  72%
  |                                                                            
  |===================================================                   |  72%
  |                                                                            
  |===================================================                   |  73%
  |                                                                            
  |====================================================                  |  74%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=====================================================                 |  75%
  |                                                                            
  |=====================================================                 |  76%
  |                                                                            
  |======================================================                |  77%
  |                                                                            
  |======================================================                |  78%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=======================================================               |  79%
  |                                                                            
  |========================================================              |  80%
  |                                                                            
  |=========================================================             |  81%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |==========================================================            |  82%
  |                                                                            
  |==========================================================            |  83%
  |                                                                            
  |==========================================================            |  84%
  |                                                                            
  |===========================================================           |  84%
  |                                                                            
  |===========================================================           |  85%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |============================================================          |  86%
  |                                                                            
  |=============================================================         |  87%
  |                                                                            
  |=============================================================         |  88%
  |                                                                            
  |==============================================================        |  88%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |===============================================================       |  89%
  |                                                                            
  |===============================================================       |  90%
  |                                                                            
  |================================================================      |  91%
  |                                                                            
  |================================================================      |  92%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |=================================================================     |  93%
  |                                                                            
  |==================================================================    |  94%
  |                                                                            
  |==================================================================    |  95%
  |                                                                            
  |===================================================================   |  95%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |====================================================================  |  97%
  |                                                                            
  |===================================================================== |  98%
  |                                                                            
  |===================================================================== |  99%
  |                                                                            
  |======================================================================|  99%
  |                                                                            
  |======================================================================| 100%
# Getting rid of US Territories
ter <- list("VI", "DC", "MP", "GU", "AS", "PR")
leaflet_map <- leaflet_map %>%
  filter(!STUSPS %in% ter) %>%
  rename(State = "NAME")

leaflet_debt <- left_join(data_1, leaflet_map, by = "State")
leaflet_debt <- st_as_sf(leaflet_debt)

content <- paste("State:", leaflet_debt$State,  "<br/>",
                 "Debt Level:", leaflet_debt$Debt_Level, "<br/>",
                 "Credit Rating:", leaflet_debt$Credit_Rating, "<br/>")
colors <- colorNumeric("Purples", domain = leaflet_debt$Debt_Level)

# Any ideas how to make the scale stronger and brighter
leaflet(leaflet_debt) %>%
  addProviderTiles("Stamen.Toner") %>%
  setView( lng = -95.71289, lat = 37.09024, zoom = 3) %>%
  addPolygons(fillColor = ~colors(leaflet_debt$Debt_Level),
               fillOpacity = 4,
               popup = ~content,
               label = leaflet_debt$State) %>%
  addLegend(pal = colors,
            values = leaflet_debt$Debt_Level,
            position = "bottomright",
            title = "Debt Level (%)") 
## Warning: sf layer has inconsistent datum (+proj=longlat +datum=NAD83 +no_defs).
## Need '+proj=longlat +datum=WGS84'